package com.mall.cart.web.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.mall.manager.pojo.TbUser;
import com.mall.pojo.TaotaoResult;
import com.mall.sso.service.TokenService;
import com.mall.utils.CookieUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Reference(timeout = 10000000)
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookieUtils.getCookieValue(request, "token");
        if (StringUtils.isEmpty(token)){
            return true;
        }
        //验证是否登录
        TaotaoResult taotaoResult = tokenService.verifyToken(token);
        if (taotaoResult.getStatus() != 200 || taotaoResult == null){
            return true;
        }

        //用户是登录状态
        TbUser user = (TbUser) taotaoResult.getData();

        //将user放到request域中，以便controller中判断访问的用户是否已经登录以便决定是否把用户的购物车信息是否和cookie中的信息合并
        //添加进去redis中
        request.setAttribute("User",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
